package com.atao.baokede.service.serviceImpl;

import com.atao.baokede.mapper.UserMapper;
import com.atao.baokede.pojo.PageBean;
import com.atao.baokede.pojo.User;
import com.atao.baokede.pojo.UserOrder;
import com.atao.baokede.pojo.UserOrderItemInformation;
import com.atao.baokede.mapper.ItemOrderMapper;
import com.atao.baokede.mapper.ItemOrderDetailMapper;
import com.atao.baokede.mapper.ItemMapper;
import com.atao.baokede.pojo.ItemOrder;
import com.atao.baokede.pojo.DetailOrder;
import com.atao.baokede.service.FileService;
import com.atao.baokede.service.UserService;
import com.atao.baokede.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private ItemOrderMapper itemOrderMapper;
    @Autowired
    private ItemOrderDetailMapper itemOrderDetailMapper;
    @Autowired
    private ItemMapper itemMapper;

    @Override
    public void register(String username, String password, String email) {
        userMapper.register(username, password, email);
    }

    @Override
    public User getUserInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();
        return userMapper.findByUserId(userId);
    }

    @Override
    public void update(User user) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();
        user.setId(userId);
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) throws Exception {
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();
        //如果用户原本就有头像，则需要删除原来的头像
        String oldAvatarUrl = userMapper.findByUserId(userId).getUserPic();
        if (oldAvatarUrl != null && !oldAvatarUrl.isEmpty()) {
            // 删除旧图片
            fileService.deletePhoto(oldAvatarUrl);
        }

        userMapper.updateAvatar(avatarUrl, userId);
    }

    @Override
    public User findByUserEmail(String email) {
        return userMapper.findByUserEmail(email);
    }

    @Override
    public void updatePwd(String email, String newPwd) {
        userMapper.updatePwd(email, newPwd);
    }

    @Override
    public void reduceBalance(Long userId, BigDecimal requestAmount) {
        userMapper.reduceBalance(requestAmount, userId);
    }

    @Override
    public User getUserInfoById(Long userId) {
        return userMapper.findByUserId(userId);
    }

    @Override
    public PageBean<UserOrder> getUserOrders(Integer status, Integer orderId, String item_name, Integer pageNum, Integer pageSize) {
        // 获取当前登录用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();

        // 使用 PageHelper 进行分页
        PageHelper.startPage(pageNum, pageSize);

        // 查询所有的订单（分页查询）
        List<UserOrder> userOrders = itemOrderMapper.findUserOrders(userId, status, orderId, item_name);

        // 强转为 Page 对象以获取分页信息
        Page<UserOrder> page = (Page<UserOrder>) userOrders;

        // 如果没有订单数据，直接返回空列表与总数
        if (userOrders == null || userOrders.isEmpty()) {
            PageBean<UserOrder> pb = new PageBean<>();
            pb.setTotal(page.getTotal());
            pb.setItems(new ArrayList<>());
            return pb;
        }

        // 提取所有商品id列表
        List<Long> itemIds = userOrders.stream()
                .filter(order -> order.getItemInformations() != null) // 非空检查
                .flatMap(order -> order.getItemInformations().stream())
                .map(UserOrderItemInformation::getItemId)
                .distinct()
                .toList();

        // 查询商品图片信息
        List<Map<String, Object>> imageRows = itemMapper.findImagesByIds(itemIds);
        Map<Long, String> imageMap = new HashMap<>();
        if (imageRows != null) {
            for (Map<String, Object> row : imageRows) {
                if (row == null) continue;
                Object iid = row.get("id");
                Object img = row.get("image");
                if (iid != null) {
                    Long k = ((Number) iid).longValue();
                    String v = img == null ? "" : String.valueOf(img);
                    imageMap.put(k, v);
                }
            }
        }

        // 填充商品图片信息
        for (UserOrder userOrder : userOrders) {
            if (userOrder.getItemInformations() != null) { // 非空检查
                for (UserOrderItemInformation itemInfo : userOrder.getItemInformations()) {
                    Long itemId = itemInfo.getItemId();
                    String image = imageMap.getOrDefault(itemId, ""); // 获取商品图片
                    itemInfo.setImage(image); // 设置商品图片
                }
            }
        }

        // 构造分页结果对象
        PageBean<UserOrder> pb = new PageBean<>();
        pb.setTotal(page.getTotal()); // 设置总记录数
        pb.setItems(userOrders); // 设置当前页数据
        return pb;
    }



}
